#include "UDPSocket.h"

UDPSocket::UDPSocket(QString ip, int port, QWidget* parent)
	:QWidget(parent)
{
	lb_port = new QLabel(QString::number(port));
	initGUI();
	this->port = port;
	r_ip->setText(ip);
	r_port->setText(QString::number(port));
	socket = new QUdpSocket(this);
	socket->bind(port);
	connect(btn_send, &QPushButton::clicked, this, &UDPSocket::SendMessage);
	connect(socket, &QUdpSocket::readyRead, this, &UDPSocket::ReceivedMessage);
}

void UDPSocket::initGUI()
{
	/* 初始化GroupBox */
	mainLayout = new QGridLayout(this);
	top_layout = new QGridLayout();
	center_layout = new QGridLayout();
	bottom_layout = new QGridLayout();
	topBox = new QGroupBox("Socket状态");
	centerBox = new QGroupBox("数据接收与提示窗口");
	bottomBox = new QGroupBox("数据发送窗口");
	below_bottom_layout = new QGridLayout();
	topBox->setLayout(top_layout);
	centerBox->setLayout(center_layout);
	bottomBox->setLayout(bottom_layout);
	mainLayout->addWidget(topBox,0,0);
	mainLayout->addWidget(centerBox,1,0);
	mainLayout->addWidget(bottomBox,2,0);
	mainLayout->addLayout(below_bottom_layout,3,0);
	mainLayout->setRowStretch(1, 1);
	mainLayout->setRowStretch(2, 1);

	/* 初始化控件 */
	top_layout->addWidget(new QLabel("本地端口："), 0, 1);
	top_layout->addWidget(lb_port, 0, 2);
	top_layout->setSpacing(10);
	top_layout->setColumnStretch(0, 1);

	t_receive = new QTextEdit();
	t_receive->setReadOnly(true);
	center_layout->addWidget(t_receive);

	t_send = new QTextEdit();
	bottom_layout->addWidget(t_send);

	btn_send = new QPushButton("发送");
	r_ip = new QLineEdit();
	r_ip->setMinimumWidth(160);
	QRegExp rx("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$");
	r_ip->setValidator(new QRegExpValidator(rx));
	r_port = new QLineEdit();
	r_port->setMaximumWidth(80);
	below_bottom_layout->addWidget(btn_send, 0, 5);
	below_bottom_layout->addWidget(new QLabel("对方IP:"), 0, 0);
	below_bottom_layout->addWidget(r_ip, 0, 1);
	below_bottom_layout->addWidget(new QLabel("对方端口："), 0, 2);
	below_bottom_layout->addWidget(r_port, 0, 3);
	below_bottom_layout->setColumnStretch(4, 1);
	below_bottom_layout->setColumnStretch(1, 1);

}

void UDPSocket::SendMessage()
{
	socket->writeDatagram(t_send->toPlainText().toUtf8(), QHostAddress(r_ip->text()), r_port->text().toInt());
	t_receive->append("本地端口[" + QString::number(port) + "]【发送】: " + t_send->toPlainText());
}

void UDPSocket::ReceivedMessage()
{
	QByteArray datagram;
	datagram.resize(socket->pendingDatagramSize());
	QHostAddress sender;
	quint16 sender_port;
	socket->readDatagram(datagram.data(), datagram.size(), &sender, &sender_port);
	QString str = sender.toString().split(":").last();
	t_receive->append(str + ":" + QString::number(sender_port) + "【接收】: " + datagram);
}
